<script setup>
import { ref, reactive,watch } from "vue";
import { getOrderList, getRemarkList, addRemark, changeOrderStatus, exportOrder } from "@/api/order";
import Pagination from "@/components/Pagination/index.vue";
import { useRouter } from "vue-router";
import { useAppStore } from "@/store/app";
import { ElMessageBox, ElMessage } from "element-plus"
import Search from "./component/search.vue"
import  {paramformat} from "@zzcpt/zztool"
import { getToken } from "@/utils/token"



const appStore = useAppStore();
const enums = appStore.enums;
const router = useRouter();
const list = ref({});
const loading = ref(false);
const searchFormRef = ref();


const imgUrl = import.meta.env.VITE_BASE_API + "/api/admin/exportOrder";



const queryParam = reactive({
  page: 1,
  company_name: '',
  mobile: '',
  post_mobile: '',
  order_sn: '',
  stime: '',
  etime: '',
  types: 1
})
const remark = reactive({
  show: false,
  remarkInfo: "",
  loading: false,
  id: 0
});
const lookReamrk = reactive({
  show: false,
  list: [],
  loading: false
})

async function getList() {
  try {
    loading.value = true;
    const res = await getOrderList(queryParam);
    list.value = [];
    if (res.data.data.length == 0) {
      loading.value = false;
      return;
    }
    list.value = res.data;
  }catch (e) {
    console.error(e)
  }finally {
    loading.value = false;
  }
}
getList();
function changePagination(e) {
  queryParam.page = e.page;
  getList();
}
function remarkFn(id) {
  remark.id = id;
  remark.show = true;
}
async function getRemarkListFn(id) {
  lookReamrk.show = true;
  lookReamrk.loading = true;
  const res = await getRemarkList({ id });
  lookReamrk.loading = false;
  lookReamrk.list = res.data;
}
async function submitRemak() {
  remark.loading = true;
  const res = await addRemark({
    id: remark.id,
    remark: remark.remarkInfo
  })
  remark.loading = false;
  if (res.code == 200) {
    remark.show = false;
    getList();
  }
}
function closeOrder(data) {
  if (data.status != 10) {
    ElMessage.warning('此订单状态无法操作');
    return;
  }

  ElMessageBox.confirm(
    '确定关闭此订单吗？',
    '提醒',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      changeOrderStatus({ id: data.id, status: 40 }).then(res => {
        if (res.code == 200) {
          ElMessage.success('订单已关闭');
          getList()
        }
      })
    })
}
function shouhouFn(data) {
  if (data.status != 90) {
    ElMessage.warning('此订单状态无法操作');
    return;
  }
  ElMessageBox.confirm(
    '是否售后',
    '提醒',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      changeOrderStatus({ id: data.id, status: 100 }).then(res => {
        if (res.code == 200) {
          ElMessage.success(res.msg);
          getList()
        }
      })
    })
}

const zhuanshouhouArr = [90, 100, 110]
function zhuanshouhouArrFn(data) {
  if (zhuanshouhouArr.includes(data.status)) {
    ElMessage.warning('此订单状态无法操作');
    return;
  }
  ElMessageBox.confirm(
    '是否售后',
    '提醒',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      changeOrderStatus({ id: data.id, status: 90 }).then(res => {
        if (res.code == 200) {
          ElMessage.success(res.msg);
          getList()
        }
      })
    })
}
function downloadFile(url) {
  var a = document.createElement('a');
  a.href = url;
  a.download = '订单列表.xls';
  a.target = '_blank';
  a.click();
}
function exportOrderFn() {
  const url = imgUrl + "?" + paramformat(Object.assign({ "admin-token": getToken() }, queryParam), 'url')
  downloadFile(url)
}

watch(() =>router.currentRoute.value.fullPath, (val) => {
  if (val) {
    const urlEnums = {
      '/order/index':1, '/order/success':2, '/order/time':3, '/order/over':4, '/order/after':5
    }
    queryParam.types = urlEnums[val];
    getList();
  }
})
</script>

<template>
  <div class="container">
    <div class="title">订单列表</div>
    <div class="box">
      <Search v-model="queryParam" @search="getList" :loading="loading" ref="searchFormRef" />
    </div>
    <div class="box mt-1" style="font-size: 14px">
      <el-table size="small" v-loading="loading" :data="list.data" style="width: 100%" row-key="id">
        <el-table-column prop="id" label="订单ID" width="80" />
        <el-table-column label="订单信息">
          <template v-slot="scope">
            <p class="font-bold">订单编号：{{ scope.row.order_sn }}</p>
            <p>下单时间：{{ scope.row.created_at }}</p>
          </template>
        </el-table-column>
        <el-table-column label="用户资料">
          <template v-slot="scope">
            <div v-if="scope.row.company">
              <p class="font-bold">{{ scope.row.company.name }}</p>
              <p>{{ scope.row.company.mobile }}</p>
            </div>
            <div v-else>
              <p class="font-bold">{{ scope.row.user.name }}</p>
              <p>用户ID：{{ scope.row.user.id }}</p>
              <p>{{ scope.row.user.mobile }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="收货地址">
          <template v-slot="scope">
            <p class="font-bold">{{ scope.row.post_address }}</p>
            <p>{{ scope.row.post_mobile }}</p>
          </template>
        </el-table-column>
        <el-table-column label="租金账单" width="200px">
          <template v-slot="scope">
            <p>总租金：￥{{ scope.row.amount }} （{{ scope.row.bill.length }}期）</p>
            <p>
              <el-tag type="info">已收：￥{{ scope.row.payed_amount }}</el-tag>
              <el-button @click="zhangdanBill(scope.row.id)" style="margin-left: 5px;" type="primary"
                size="small">账单</el-button>
            <p v-if="scope.row.status == 80" class="font-bold" style="color: #f00;">逾期天数：{{ scope.row.overdue_days }}
            </p>
            </p>

          </template>
        </el-table-column>
        <el-table-column label="订单状态">
          <template v-slot="scope">
            <p class="font-bold">{{ enums[scope.row.status] }}</p>
          </template>
        </el-table-column>
        <el-table-column label="订单备注">
          <template v-slot="scope">
            <p class="font-bold">
              {{ scope.row.remark ? scope.row.remark : "/" }}
            </p>
            <el-button type="primary" size="small" @click="getRemarkListFn(scope.row.id)">备注记录</el-button>
          </template>
        </el-table-column>
        <el-table-column label="用户备注">
          <template v-slot="scope">
            <p class="font-bold">
              {{ scope.row.buyer_remark ? scope.row.buyer_remark : "/" }}
            </p>
          </template>
        </el-table-column>
        <el-table-column label="其他">
          <template v-slot="scope">
            <p class="font-bold">
              租期：{{ scope.row.start_date }}~{{ scope.row.end_date }}
            </p>
            <p>审核员：{{ scope.row.admin?.real_name || '/' }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" text size="small">
              <RouterLink :to="'/order/detail/' + scope.row.id" target="_blank">
                详情
              </RouterLink>
            </el-button>
            <el-button type="primary" text size="small" @click="remarkFn(scope.row.id)">备注</el-button>
            <el-button v-if="scope.row.status == 10" type="warning" text size="small"
              @click="closeOrder(scope.row)">关闭订单</el-button>
            <el-button v-if="scope.row.status == 90" type="primary" text size="small"
              @click="shouhouFn(scope.row)">售后完成</el-button>
            <el-button v-if="!zhuanshouhouArr.includes(scope.row.status)" text size="small"
              @click="zhuanshouhouArrFn(scope.row)">转售后</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination @pagination="changePagination" :total="list.total" :page="list.current_page" />
    </div>
  </div>
  <el-dialog :close-on-click-modal="false" draggable v-model="remark.show" title="订单备注" width="800">
    <el-input v-model="remark.remarkInfo" :autosize="{ minRows: 6, maxRows: 6 }" type="textarea" placeholder="请输入" />
    <div class="text-center">
      <el-button :loading="remark.loading" type="primary" style="margin-top: 20px" @click="submitRemak()">确定</el-button>
    </div>
  </el-dialog>
  <el-dialog draggable v-model="lookReamrk.show" title="备注列表" width="500">
    <ul v-loading="lookReamrk.loading" class="reamrk-list">
      <li v-for="item in lookReamrk.list" :key="item.id" class="flex w-full mt-1">
        <el-avatar style="width: 30px;height:30px;min-width: 30px;" class="mr-1"
          src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
        <div class="w-full">
          <div class="flex flex-j-b">
            <span>{{ item.admin_name }}</span>
            <span>{{ item.created_at }}</span>
          </div>
          <div>
            <p>备注：{{ item.remark }}</p>
          </div>
        </div>
      </li>
    </ul>
    <el-empty v-if="lookReamrk.list.length == 0" description="未查询到数据" />
    <div class="text-center">
      <el-button type="primary" style="margin-top: 20px" @click="lookReamrk.show = false">确定</el-button>
    </div>
  </el-dialog>
</template>
<style scoped>
.reamrk-list {
  list-style: none;
}
</style>